import {menus} from '../assets/settings.json'

import {Breadcrumb, MenuProps} from "antd";

import {ReactNode} from "react";
import {Link, NavLink} from "react-router-dom";

import LazyIcon from "../components/Tools/Icon";

export type MenuItem = Required<MenuProps>['items'][number];

export interface Menu {
    label: string;
    url: string;
    iconName?: string;
    subs?: Menu[] | []
}

const flattenedMenuDataArr = function flatten(): Menu[] {
    const flattenedMenuUrls: Menu[] = []

    function doFlatten(items: Menu[]) {
        for (const item of items) {
            flattenedMenuUrls.push(item)

            if (item.subs) {
                doFlatten(item.subs)
            }
        }
    }

    doFlatten(menus)
    return flattenedMenuUrls
}()

export function getMenu(url: string) {
    return flattenedMenuDataArr.find((item: Menu) => item.url === url) as Menu;
}

export function getMenuItems(): MenuItem[] {
    function construct(menus: Menu[]): MenuItem[] {
        return menus.map((item) => {
            let children = undefined
            if (item.subs && item.subs.length > 0) {
                children = construct(item.subs)
            }

            const {label, url, iconName} = item
            return {
                key: url, label: <NavLink to={`/dashboard${url}`}>{label}</NavLink>, icon: LazyIcon({iconName}), children
            } as MenuItem;
        })
    }

    return construct(menus);
}

/**
 * Description: 组织面包屑.
 */
export function getBreadcrumbItems(pathname: string): ReactNode {
    pathname = getRealPathname(pathname);
    return pathname.split('/').map((_: string, index: number) => {
        const segment = pathname.split('/').filter((_: string | null) => _).slice(0, index).filter((_: string | null) => _).join('/')
        if (!segment) {
            return null;
        }

        const url = `/${segment}`
        const {iconName, label} = getMenu(url)

        return (
            <Breadcrumb.Item key={url}>
                {LazyIcon({iconName})}
                <Link to={`/dashboard${url}`}>
                    <span>{label}</span>
                </Link>
            </Breadcrumb.Item>
        )
    }).filter(Boolean)
}

export function getRealPathname(pathname: string): string {
    return pathname.replace(/\/dashboard/, "")
}
